package com.iwunu.gateway.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.cache.RedisService;
import com.iwunu.gateway.config.UrlConfig;
import com.iwunu.gateway.constant.ApartmentConstant;
import com.iwunu.gateway.entity.CmdIssued;
import com.iwunu.gateway.entity.FLockMember;
import com.iwunu.gateway.entity.FaceLock;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.service.CmdIssuedMongodbService;
import com.iwunu.gateway.service.FaceLockMemberService;
import com.iwunu.gateway.service.FaceLockService;
import com.iwunu.gateway.service.FacesLogMongodbService;
import com.iwunu.gateway.service.FlockLogService;
import com.iwunu.gateway.service.ImageFeatureService;
import com.iwunu.gateway.service.ImageMongodbService;
import com.iwunu.gateway.service.TokenService;
import com.iwunu.gateway.util.ComUtil;
import com.iwunu.gateway.util.FeatureSoUtil;
import com.iwunu.gateway.util.FileUtils;
import com.iwunu.gateway.util.PitNumUtil;
import com.iwunu.gateway.vo.CmdIssuedLineVo;
import com.iwunu.gateway.vo.CmdIssuedVo;
import com.iwunu.gateway.vo.LogVo;
import com.iwunu.gateway.vo.UserCmdIssuedVo;
import com.iwunu.iot.common.constant.ClientOpenTypeEnum;
import com.iwunu.iot.common.constant.Constant;
import com.iwunu.iot.common.constant.ResultCodeEnum;
import com.iwunu.iot.common.util.HexUtils;
import com.iwunu.iot.common.util.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiParam;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@Controller
@Api(value = "fackLock/api", tags = "门锁APP控制接口", description = "门锁APP控制接口")
public class FacesLockApiController {
	private final static Logger logger = LoggerFactory.getLogger(FacesLockApiController.class);
	@Autowired
	public RedisService redisService;
	@Autowired
	public FaceLockService faceLockService;
	@Autowired
	public FlockLogService flockLogService;
	@Autowired
	private ImageMongodbService imageMongodbService;
	@Autowired
	private CmdIssuedMongodbService cmdIssuedMongodbService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private FaceLockMemberService faceLockMemberService;
	@Autowired
	private ImageFeatureService imageFeatureService;
	@Autowired
	private UrlConfig urlConfig;
	@Autowired
	private FacesLogMongodbService facesLogMongodbService;
	private static final String fileUploadPath = "/opt/img";
	private static final Integer hc_out_admin_role = 11;

	/**
	 ** 下发密码
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@CrossOrigin(origins = "*")
	@ApiImplicitParams({ @ApiImplicitParam(name = "cmdIssuedVos", value = "{\"cmdData\":[{\"data\":\"258369\""
			+ ",\"startTime\":\"2021-06-10 00:00:00\",</br>\"endTime\":\"2021-06-10 00:00:00\"}]}", required = true, dataType = "String", paramType = "body") })
	@RequestMapping(value = "/iot/cmdpwd/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cmdpwd(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		if (cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdData"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		String code = cmdIssuedMongodbService.saveSendImageData(cmdList, Authorization, lockId.toString(),
				ClientOpenTypeEnum.PASSWORD.getType(), hc_out_admin_role);
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.OVER_PITNUM.getCode(), ResultCodeEnum.OVER_PITNUM.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 下发卡号
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@CrossOrigin(origins = "*")
	@ApiImplicitParams({ @ApiImplicitParam(name = "cmdIssuedVos", value = "{\"cmdData\":[{\"data\":\"C90178CF\""
			+ ",\"startTime\":\"2021-06-10 00:00:00\",</br>\"endTime\":\"2021-06-10 00:00:00\"}]}", required = true, dataType = "String", paramType = "body") })
	@RequestMapping(value = "/iot/cmdCardNo/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cmdCardNo(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		if (cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdData"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		String code = cmdIssuedMongodbService.saveSendImageData(cmdList, Authorization, lockId.toString(),
				ClientOpenTypeEnum.PASSWORD.getType(), hc_out_admin_role);
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
					null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 下发密码
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@CrossOrigin(origins = "*")
	@ApiImplicitParams({ @ApiImplicitParam(name = "cmdIssuedVos", value = "{\"cmdData\":[{\"data\":\"258369\""
			+ ",\"startTime\":\"2021-06-10 00:00:00\",</br>\"endTime\":\"2021-06-10 00:00:00\"}]}", required = true, dataType = "String", paramType = "body") })
	@RequestMapping(value = "/iot/password/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cmdIssued(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdData"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		String code = cmdIssuedMongodbService.saveSendImageData(cmdList, userId, flock.getLockClientId(),
				ClientOpenTypeEnum.PASSWORD.getType(), flock.getRole());
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.OVER_PITNUM.getCode(), ResultCodeEnum.OVER_PITNUM.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 下发卡号
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@CrossOrigin(origins = "*")
	@ApiImplicitParams({ @ApiImplicitParam(name = "cmdIssuedVos", value = "{\"cmdData\":[{\"data\":\"C90178CF\""
			+ ",\"startTime\":\"2021-06-10 00:00:00\",</br>\"endTime\":\"2021-06-10 00:00:00\"}]}", required = true, dataType = "String", paramType = "body") })
	@RequestMapping(value = "/iot/cardNo/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cardNo(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdData"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		String code = cmdIssuedMongodbService.saveSendImageData(cmdList, userId, flock.getLockClientId(),
				ClientOpenTypeEnum.CARD.getType(), flock.getRole());
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
					null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 蓝牙获取添加卡信息
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiImplicitParams({ @ApiImplicitParam(name = "cmdIssuedVo", value = "{\"cmdIssuedVo\":{\"data\":\"C90178CF\""
			+ ",\"remark\":\"添加卡\",\"pitNum\":1}]}", required = true, dataType = "String", paramType = "body") })
	@RequestMapping(value = "/iot/bleCardNo/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> bleCardNo(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);

		CmdIssued exitCmd = cmdIssuedMongodbService.getExitBleSendCmdByData(flock.getLockClientId(),
				ClientOpenTypeEnum.CARD.getType(), flock.getLockClientId() + ClientOpenTypeEnum.CARD.getType());
		if (exitCmd != null) {
			result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdIssuedVo"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		CmdIssued cmd = cmdIssuedMongodbService.getBleSendCmdByData(flock.getLockClientId(),
				ClientOpenTypeEnum.CARD.getType(), cmdList.get(0).getPitNum());
		if (cmd == null) {
			result = new Result(ResultCodeEnum.UPLOAD_ERROR.getCode(), ResultCodeEnum.UPLOAD_ERROR.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		cmd.setUserId(userId);
		cmd.setRole(flock.getRole());
		cmd.setData(cmdList.get(0).getData());
		cmd.setRemark(cmdList.get(0).getRemark());
		cmdIssuedMongodbService.updateBleCmd(cmd);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 蓝牙添加指纹
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/bleFinger/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> bleFinger(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody JSONObject cmdIssuedVos) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		CmdIssued exitCmd = cmdIssuedMongodbService.getExitBleSendCmdByData(flock.getLockClientId(),
				ClientOpenTypeEnum.FINGER.getType(), flock.getLockClientId() + ClientOpenTypeEnum.FINGER.getType());
		if (exitCmd != null) {
			result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String cmds = JSONArray.toJSONString(cmdIssuedVos.get("cmdIssuedVo"));
		List<CmdIssuedVo> cmdList = JSONArray.parseArray(cmds, CmdIssuedVo.class);
		CmdIssued cmd = cmdIssuedMongodbService.getBleSendCmdByData(flock.getLockClientId(),
				ClientOpenTypeEnum.FINGER.getType(), cmdList.get(0).getPitNum());
		if (cmd == null) {
			result = new Result(ResultCodeEnum.UPLOAD_ERROR.getCode(), ResultCodeEnum.UPLOAD_ERROR.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		System.out.println("cmdIssuedVos :" + cmdIssuedVos.toJSONString());

		cmd.setUserId(userId);
		cmd.setRole(flock.getRole());
		cmd.setData(cmdList.get(0).getData());
		cmd.setRemark(cmdList.get(0).getRemark());
		cmdIssuedMongodbService.updateBleCmd(cmd);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 下发指纹
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/iot/finger/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> finger(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody List<CmdIssuedVo> cmdIssuedVos) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String code = cmdIssuedMongodbService.saveSendImageData(cmdIssuedVos, userId, flock.getLockClientId(),
				ClientOpenTypeEnum.CARD.getType(), flock.getRole());
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
					null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 更新人脸使用时长
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/updateFace/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> updateFace(@RequestHeader String Authorization,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @RequestParam("pitNum") Integer pitNum,
			@ApiParam(value = "有效开始时间", required = true) @RequestParam("startTime") String startTime,
			@ApiParam(value = "有效结束时间", required = true) @RequestParam("endTime") String endTime) throws Exception {
		Result result = null;
		Integer type = ClientOpenTypeEnum.FACES.getType();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String delKey = flock.getLockClientId() + ClientOpenTypeEnum.DELFACES.getData();
		ImageMongo image = imageMongodbService.getImageByDeviceId(flock.getLockClientId(), pitNum);
		redisService.rightPush(delKey, pitNum.toString());
		imageMongodbService.updateImage(flock.getLockClientId(), pitNum, endTime, startTime);
		JSONObject json = new JSONObject();
		json.put("flDeviceId", Authorization);
		json.put("clientId", flock.getLockClientId());
		json.put("pitNum", pitNum);
		json.put("size", image.getImageData().length);
		json.put("startTime", startTime);
		json.put("endTime", endTime);
		redisService.rightPush(flock.getLockClientId() + "##_" + type, json.toJSONString());
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 远程开锁
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/openLock/{lockId}/{status}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> openLock(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
			@ApiParam(value = "开门状态", required = true) @PathVariable("status") Integer status) {
		Result result = null;
		String type = ClientOpenTypeEnum.OPEN.getData();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId.intValue());
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getLockClientId() + type;
		if (redisService.get(key) == null) {
			redisService.setex(key, 120, status.toString());
			flockLogService.saveLog(userId, status.toString(), flock.getLockClientId(), lockId,
					ClientOpenTypeEnum.OPEN.getType(), flock.getRole());
		}
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除密码
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/iot/delPwd/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delPwd(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELPWD.getData();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getLockClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除卡
	 * 
	 * @return
	 */
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/iot/delCard/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delCard(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELCARD.getData();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getLockClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 蓝牙删除卡
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/delBleCard/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delBleCard(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.DELCARD.getType();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		cmdIssuedMongodbService.removeCmd(flock.getLockClientId(), pitNum, type);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 鍒犻櫎鎸囩汗
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/delBleFinger/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delBleFinger(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.DELFINGER.getType();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		cmdIssuedMongodbService.removeCmd(flock.getLockClientId(), pitNum, type);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除指纹
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/delFinger/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delFinger(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELFINGER.getData();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getLockClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除人脸
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/delFaces/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delFaces(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELFACES.getData();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getLockClientId() + type;
		System.out.println("delFaces + pitNum:" + pitNum);
		ImageMongo imageMongo = imageMongodbService.getImageByDeviceId(flock.getLockClientId(), pitNum);
		redisService.rightPush(key, pitNum.toString());
		imageMongodbService.updateImage(imageMongo.getClientId(), pitNum);
//        FileUtils.deleteFile(imageMongo.getImageUrl());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 清除所有数据
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/clear/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> clear(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		String typepwd = ClientOpenTypeEnum.DELPWD.getData();
		String typecard = ClientOpenTypeEnum.DELCARD.getData();
		String typefingle = ClientOpenTypeEnum.DELFINGER.getData();
		String typefaces = ClientOpenTypeEnum.DELFACES.getData();
		FaceLock flock = faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getClientId() + typepwd;
		redisService.rightPush(key, ApartmentConstant.pitNum.toString());
		key = flock.getClientId() + typecard;
		redisService.rightPush(key, ApartmentConstant.pitNum.toString());
		key = flock.getClientId() + typefingle;
		redisService.rightPush(key, ApartmentConstant.pitNum.toString());
		key = flock.getClientId() + typefaces;
		redisService.rightPush(key, ApartmentConstant.imagePitNum.toString());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 人脸列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/facesList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> facesList(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		String type = ClientOpenTypeEnum.FACES.getData();
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null || fl.isEmpty()) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		List<UserCmdIssuedVo> userCmdIssueds = faceLockService.getUserImageData(fl);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 鑾峰彇鐢ㄦ埛浜鸿劯
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/passwordList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> passwordList(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.PASSWORD.getType();
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		List<UserCmdIssuedVo> userCmdIssueds = faceLockService.getUserCmdIssude(fl, type);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 卡列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/cardList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> cardList(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.CARD.getType();
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		List<UserCmdIssuedVo> userCmdIssueds = faceLockService.getUserCmdIssude(fl, type);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 指纹列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/fingleList/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> fingleList(@RequestHeader String Authorization,
			@ApiParam(value = "閿両d", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		Integer type = ClientOpenTypeEnum.FINGER.getType();
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		List<UserCmdIssuedVo> userCmdIssueds = faceLockService.getUserCmdIssude(fl, type);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), userCmdIssueds);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 开锁日志
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/loglist/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> loglist(@RequestHeader String Authorization,
			@ApiParam(value = "姣忛〉鏄剧ず鏁伴噺", required = true) @RequestParam("pageSize") Integer pageSize,
			@ApiParam(value = "褰撳墠椤�", required = true) @RequestParam("pageNum") Integer currentPage,
			@RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime ", required = false) String endTime,
			@RequestParam(value = "openType", required = false) Integer openType,
			@RequestParam(value = "isSucc", required = false) boolean isSucc,
			@RequestParam(value = "isOwner", required = true) boolean isOwner,
			@ApiParam(value = "閿両d", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		LogVo log = new LogVo();
		log.setCurrentPage(currentPage);
		log.setStartTime(startTime);
		log.setEndTime(endTime);
		log.setOwner(isOwner);
		log.setPageSize(pageSize);
		log.setSucc(isSucc);
		log.setType(openType);
		Map<String, Object> logs = null;
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		if (!log.isOwner()) {
			logs = facesLogMongodbService.getOtherLog(lockId, userId, fl.get("lockclientid").toString(), log,
					Integer.valueOf(fl.get("role").toString()));
		} else {
			logs = facesLogMongodbService.getMyLog(fl, log);
		}
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), logs);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 更新联网状态
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/updateNetWorK/{lockId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> updateNetWorK(@RequestHeader String Authorization,
			@ApiParam(value = "閿両d", required = true) @PathVariable("lockId") Integer lockId,
			@RequestParam(value = "netWorkStatus", required = true) Integer netWorkStatus) {
		Result result = null;
		FaceLock fl = faceLockService.getFaceLockByUUID(Long.valueOf(lockId));
		if (fl == null) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		fl.setNetWorkStatus(netWorkStatus);
		faceLockService.update(fl);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 保存蓝牙开锁日志
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/log/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> log(@RequestHeader String Authorization,
			@ApiParam(value = "閿両d", required = true) @PathVariable("lockId") Integer lockId) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		Map<String, Object> fl = faceLockMemberService.findLockInfo(Integer.valueOf(userId), lockId);
		if (fl == null || fl.isEmpty()) {
			result = new Result(ResultCodeEnum.NOT_GATEWAY.getCode(), ResultCodeEnum.NOT_GATEWAY.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		flockLogService.saveBleLog(userId, "10", lockId.toString(), 10, Integer.valueOf(fl.get("role").toString()));
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	public static void main(String[] args) {
	}

	/**
	 ** 删除下发指令
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/delCmd/{lockId}/{pitNum}/{type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delCmd(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum,
			@ApiParam(value = "下发型", required = true) @PathVariable("type") Integer type// 7密码，8卡，6指纹
	) {
		Result result = null;
		if (type == 7) {
			String fun = ClientOpenTypeEnum.DELCARD.getData();
			String userId = tokenService.parseToken(Authorization);
			FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
			if (StringUtils.isEmpty(Authorization) || flock == null) {
				result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),
						null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			String key = flock.getLockClientId() + fun;
			redisService.rightPush(key, pitNum.toString());
			cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
			result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		} else {
			String fun = ClientOpenTypeEnum.DELCARD.getData();
			String userId = tokenService.parseToken(Authorization);
			FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
			if (StringUtils.isEmpty(Authorization) || flock == null) {
				result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),
						null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			String key = flock.getLockClientId() + fun;
			redisService.rightPush(key, pitNum.toString());
			cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELPWD.getType());
			result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
	}

	/**
	 ** 下发语音
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/advert/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> advert(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@RequestBody List<CmdIssuedVo> cmdIssuedVos) {
		Result result = null;
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null || cmdIssuedVos.size() <= 0) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String code = cmdIssuedMongodbService.saveSendImageData(cmdIssuedVos, userId, flock.getLockClientId(),
				ClientOpenTypeEnum.ADVERT.getType(), flock.getRole());
		if (code.isEmpty()) {
			result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
					null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	/**
	 ** 删除广告
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/delAdvert/{lockId}/{pitNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delAdvert(@RequestHeader String Authorization,
			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "坑位", required = true) @PathVariable("pitNum") Integer pitNum) {
		Result result = null;
		String type = ClientOpenTypeEnum.DELADVERT.getData();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String key = flock.getLockClientId() + type;
		redisService.rightPush(key, pitNum.toString());
		cmdIssuedMongodbService.updateCmd(flock.getLockClientId(), pitNum, ClientOpenTypeEnum.DELADVERT.getType());
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	@RequestMapping(value = "/delRedisKey",  method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> delRedisKey(@RequestParam(value = "clientId", required = false) String clientId) {
		Result result = null;
		redisService.delKeys(clientId);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	/**
	 ** 人脸图像下发
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/facesImage/{lockId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> uploadThumbnail(@RequestHeader String Authorization,
			@RequestParam("facesImage") MultipartFile[] multipartFiles,
			@ApiParam(value = "锁ID", required = true) @PathVariable("lockId") Integer lockId,
			@ApiParam(value = "备注", required = true) @RequestParam("remark") String remark,
			@ApiParam(value = "有效开始时间", required = true) @RequestParam("startTime") String startTime,
			@ApiParam(value = "有效结束时间", required = true) @RequestParam("endTime") String endTime) throws Exception {

		Result result = null;
		Integer type = 1;
		byte[] imageData = null;
		byte[] imageDataFeature = null;
		JSONObject json = new JSONObject();
		String userId = tokenService.parseToken(Authorization);
		FLockMember flock = faceLockMemberService.findFaceLockMember(Integer.valueOf(userId), lockId);
		if (StringUtils.isEmpty(Authorization) || flock == null) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		FaceLock lock = faceLockService.getFaceLockByUUID(Long.parseLong(lockId.toString()));
		List<ImageMongo> images = imageMongodbService.getSendImageData(flock.getLockClientId());
		if (images.size() > ApartmentConstant.imagePitNum) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}

		if (!ComUtil.isEmpty(multipartFiles) && multipartFiles.length != 0) {
			for (MultipartFile multipartFile : multipartFiles) {
				Integer pitNum = PitNumUtil.getImagePitNum(images);
				String postFix = multipartFile.getOriginalFilename()
						.split("//.")[multipartFile.getOriginalFilename().split("//.").length - 1];
				if (Arrays.asList(Constant.FilePostFix.IMAGES).contains(postFix)) {
					result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(),
							ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
					return new ResponseEntity<>(result, HttpStatus.OK);
				}
				String url = FileUtils.fileSave(multipartFile.getInputStream(), 1, multipartFile.getOriginalFilename(),
						null);
				String preUrl = FileUtils.thumbnails(url, url);
				if (StringUtils.isEmpty(preUrl)) {
					result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(),
							ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
					return new ResponseEntity<>(result, HttpStatus.OK);
				}
				if (lock.getIsNewLock() != null && lock.getIsNewLock()) {
					json = FeatureSoUtil.invoke(preUrl);
					type = ClientOpenTypeEnum.FM226FEATURE.getType();
					imageDataFeature = json.getString("data").getBytes();
				} else if (lock.getIsNewLock() == null || lock.getIsNewLock()) {
					type = ClientOpenTypeEnum.FACES.getType();
					imageDataFeature = imageFeatureService.getImageFeature(multipartFile.getBytes());
					if (imageDataFeature == null) {
						result = new Result(ResultCodeEnum.CMDISSUED_FAIL.getCode(),
								ResultCodeEnum.CMDISSUED_FAIL.getDesc(), null);
						return new ResponseEntity<>(result, HttpStatus.CREATED);
					}
					String data = HexUtils.bytesToHexString(imageDataFeature, imageDataFeature.length);
					imageData = FileUtils.getImageFromLocalByUrl(preUrl);
					preUrl = urlConfig.getImageHost() + preUrl.replace(fileUploadPath, "");
					json.put("feature", data);
					json.put("size", imageData.length);

				}
				preUrl = urlConfig.getImageHost() + preUrl.replace(fileUploadPath, "");
				ImageMongo imageMongo = imageMongodbService.saveSendImageData(startTime, endTime, imageData,
						imageDataFeature, userId, pitNum, preUrl, flock.getLockClientId(), flock.getRole(), remark);
				json.put("flDeviceId", flock.getLockClientId());
				json.put("clientId", flock.getLockClientId());
				json.put("pitNum", pitNum);
				json.put("startTime", startTime);
				json.put("endTime", endTime);
				redisService.rightPush(flock.getLockClientId() + "##_" + type, json.toJSONString());
				redisService.rightPush(flock.getLockClientId() + "##_" + ClientOpenTypeEnum.FACES.getType(),
						json.toJSONString());
//					FileUtils.deleteFile(url);
			}
		}
		result = new Result(ResultCodeEnum.CMDISSUED_SUCCESS.getCode(), ResultCodeEnum.CMDISSUED_SUCCESS.getDesc(),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
//	/**
//	 ** 人脸图像下发
//	 * 
//	 * @return
//	 */
//	@SuppressWarnings({ "unchecked", "rawtypes" })
//	@RequestMapping(value = "/iot/feature", method = RequestMethod.POST)
//	public ResponseEntity<Result> uploadFeature(
//			@ApiParam(value = "锁Id", required = true) @PathVariable("lockId") Long lockId,
//			@RequestParam("facesImage") MultipartFile multipartFile,
//			@ApiParam(value = "坑位", required = true) @RequestParam("pitNum") Integer pitNum,
//			@ApiParam(value = "有效开始时间", required = true) @RequestParam("startTime") String startTime,
//			@ApiParam(value = "有效结束时间", required = true) @RequestParam("endTime") String endTime) throws Exception {
//		Result result = null;
//		CmdIssuedLineVo cmdIssuedVo = new CmdIssuedLineVo();
//		Integer type = ClientOpenTypeEnum.FACES.getType();
//		FaceLock flock = faceLockService.getFaceLockByUUID(lockId);
//		byte[] imageData = imageFeatureService.getImageFeature(multipartFile.getBytes());
//		if(imageData==null) {
//			result = new Result(ResultCodeEnum.CMDISSUED_FAIL.getCode(), ResultCodeEnum.CMDISSUED_FAIL.getDesc(),null);
//			return new ResponseEntity<>(result, HttpStatus.CREATED);
//		}
//		String data =  HexUtils.bytesToHexString(imageData, imageData.length);
//		JSONObject json = new JSONObject();
//		json.put("flDeviceId", flock.getClientId());
//		json.put("clientId", flock.getClientId());
//		json.put("pitNum", pitNum);
//		json.put("startTime", startTime);
//		json.put("endTime", endTime);
//		json.put("data", data);
//		cmdIssuedVo.setData(data);
//		cmdIssuedVo.setStartTime(startTime);
//		cmdIssuedVo.setEndTime(endTime);
//		cmdIssuedVo.setPitNum(pitNum);
//		cmdIssuedService.saveSendData(cmdIssuedVo, flock.getClientId(),  type);
//        result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(),null);
//       return new ResponseEntity<>(result, HttpStatus.OK);
//	}

	/**
	 ** 人脸图像下发
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/iot/getFeature", method = RequestMethod.POST)
	public ResponseEntity<Result> sendFeature(@RequestParam("facesImage") MultipartFile multipartFile)
			throws Exception {
		Result result = null;
		JSONObject resultJson = new JSONObject();
		CmdIssuedLineVo cmdIssuedVo = new CmdIssuedLineVo();
		if (multipartFile == null || ComUtil.isEmpty(multipartFile)) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		String url = FileUtils.fileSave(multipartFile.getInputStream(), 1, multipartFile.getOriginalFilename(), null);
		String preUrl = FileUtils.thumbnails(url, url);
		if (StringUtils.isEmpty(preUrl)) {
			result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		try {
			resultJson = FeatureSoUtil.invoke(preUrl);
			if (resultJson == null) {
				if (StringUtils.isEmpty(preUrl)) {
					result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(),
							ResultCodeEnum.INVALID_PARAMS.getDesc(), null);
					return new ResponseEntity<>(result, HttpStatus.OK);
				}
			}

			if (resultJson.getString("data").length() < 2048) {
				result = new Result(ResultCodeEnum.INVALID_FEATURE.getCode(), ResultCodeEnum.INVALID_FEATURE.getDesc(),
						resultJson.getString("code"), null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
		} catch (Exception e) {
			result = new Result(ResultCodeEnum.INVALID_FEATURE.getCode(), ResultCodeEnum.INVALID_FEATURE.getDesc(),
					null, null);
			return new ResponseEntity<>(result, HttpStatus.OK);
		}
		FileUtils.deleteFile(url);
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), resultJson.getString("data"),
				null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	/**
	 ** 远程OTA
	 * 
	 * @return
	 */
	@RequestMapping(value = "/iot/ota", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<Result> ota(@RequestHeader String Authorization,
			@RequestParam("otaBin") MultipartFile multipartFile,
			@ApiParam(value = "版本号", required = true) @RequestParam("version") String version) {
		Result result = null;
		JSONObject sendData = new JSONObject();
		try {
			String url = FileUtils.fileSave(multipartFile.getInputStream(), 2, multipartFile.getOriginalFilename(),
					null);

			if (StringUtils.isEmpty(Authorization)) {
				result = new Result(ResultCodeEnum.INVALID_PARAMS.getCode(), ResultCodeEnum.INVALID_PARAMS.getDesc(),
						null);
				return new ResponseEntity<>(result, HttpStatus.OK);
			}
			String clientId = tokenService.parseDeviceToken(Authorization);
			Integer vs = Integer.parseInt(version.replaceAll("\\D", ""));
			String type = ClientOpenTypeEnum.OTA.getData();
			sendData.put("md5Str", type);
			sendData.put("data", url);
			sendData.put("md5Str", clientId);
			sendData.put("version", vs);
			sendData.put("packSize", multipartFile.getSize() / 2);
			redisService.set(clientId + type, sendData.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		result = new Result(ResultCodeEnum.OK.getCode(), ResultCodeEnum.OK.getDesc(), null);
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	
}
